<template>
	<view>
		<u-popup v-model="localShow" mode="bottom">
			<view class="product-operation-arar">
				<view>
					<view class="u-flex u-padding-25 u-row-between">
						<text class="u-color-666666" @click="handleCancel">取消</text>
						<text class="xl bold">产品管理</text>
						<text class="u-color-0099FF" @click="handleConfirm">确认</text>
					</view>

					<view v-if="businessCardInformation.is_vip != 1" 
						class="hint-buy-vip-area u-flex u-row-between u-padding-20 u-margin-25">
						<text class="nr bold u-color-0099FF">名片已锁定,客户无法查看到您的信息!</text>
						<view class="go-buy-btn xs u-font-weight-500">立即解锁</view>
					</view>
				</view>
				<scroll-view scroll-y style="height: 83vh;">
					<view class="product-lists-area">
						<view v-for="(item, index) in productList" :key="item.id"
							class="product-item u-margin-25 u-border-radius-10 bg-white u-padding-25">
							<view class="u-flex">
								<view class="u-flex u-flex-1">
									<text class="u-padding-right-15 xl bold din-font">{{ item.name }}</text>
									<u-tag :text="item.advantage" />
								</view>
								<view class="u-flex u-row-between">
									<u-icon name="edit-pen" color="#2979ff" size="28" class="u-padding-right-10"
										@click="handleEdit(item)"></u-icon>
									<u-icon name="trash" color="#2979ff" size="28" @click="handleDelete(item)"></u-icon>
								</view>
							</view>
							<view class="u-flex u-padding-top-20">
								<view class="u-flex-1 u-flex">
									<view class="u-flex-1">
										<view class="u-flex-baseline u-line-1">
											<text class="xxxl u-color-0099FF bold u-line-1 din-font">{{ item.limit }}</text>
											<text class="xs gray u-padding-left-5">万</text>
										</view>
										<view class="xs gray u-margin-top-5">最高额度</view>
									</view>
									<view class="u-flex-1">
										<view class="u-flex-baseline u-line-1">
											<text class="xxxl u-color-0099FF bold u-line-1 din-font">{{ item.rate }}</text>
											<text class="xs gray u-padding-left-5">%</text>
										</view>
										<view class="xs gray u-margin-top-5">年化利率</view>
									</view>
									<view class="u-text-center">
										<u-switch v-model="item.is_show" :size="35" :active-value="1"
											:inactive-value="0" @change="handleRecommendChange(item)"></u-switch>
										<view class="xs u-padding-top-10 gray">底部展示</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view @click="showAddProduct"
						class="add-product-area u-flex u-padding-25 bg-white u-margin-25 u-border-radius-10">
						<u-icon name="plus-circle-fill" size="70" class="u-color-0099FF"></u-icon>
						<view class="u-padding-left-15">
							<view class="nr bold u-padding-bottom-5">添加产品</view>
							<view class="xs u-color-666666">可展示5款产品，精准锁定用户，提升品牌曝光与转化率，助您抢占市场先机！</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>

		<u-popup v-model="showAddForm" mode="bottom" border-radius="33">
			<view class="popup-bg">
				<view class="form-area-bg">
					<view class="form-area">
						<u-form ref="uForm" :model="formData" :error-type="['toast']" :rules="rules">
							<u-form-item prop="name" labelWidth="170" label="产品名称"
								:leftIcon="'https://resource.lanbaozixun.com/uploads/images/20240723161417bca3a8105.png'"
								:leftIconStyle="{
                                    width: '38rpx',
                                    height: '38rpx',
                                    position: 'relative',
                                    transform: 'translateY(25%)'
                                }" :border-bottom="false">
								<u-input v-model="formData.name" placeholder="请输入产品名称" />
							</u-form-item>

							<u-form-item prop="limit" labelWidth="170" label="最高额度"
								:leftIcon="'https://resource.lanbaozixun.com/uploads/images/202407231614175e2115595.png'"
								:leftIconStyle="{
                                    width: '38rpx',
                                    height: '38rpx',
                                    position: 'relative',
                                    transform: 'translateY(25%)'
                                }" :border-bottom="false">
								<u-input v-model="formData.limit" placeholder="请输入最高额度" type="number" />
								<view>万元</view>
							</u-form-item>

							<u-form-item prop="rate" labelWidth="170" label="年化利率"
								:leftIcon="'https://resource.lanbaozixun.com/uploads/images/20240723161450537302785.png'"
								:leftIconStyle="{
                                    width: '38rpx',
                                    height: '38rpx',
                                    position: 'relative',
                                    transform: 'translateY(25%)'
                                }" :border-bottom="false">
								<u-input v-model="formData.rate" placeholder="请输入年化利率" type="number" />
							</u-form-item>

							<u-form-item prop="advantage" labelWidth="170" label="产品优势"
								:leftIcon="'https://resource.lanbaozixun.com/uploads/images/20240723161417a2e6c4450.png'"
								:leftIconStyle="{
                                    width: '38rpx',
                                    height: '38rpx',
                                    position: 'relative',
                                    transform: 'translateY(25%)'
                                }" :border-bottom="false">
								<u-input v-model="formData.advantage" placeholder="请输入产品优势" />
							</u-form-item>
						</u-form>

						<u-button type="primary" :custom-style="{
                            width: '90%',
                            margin: '40rpx auto 0',
                            borderRadius: '100rpx',
                            background: 'linear-gradient(180deg, #6BB2FF 0%, #437EEA 100%)'
                        }" @click="submitForm">保存</u-button>

						<view class="u-tips-color u-text-center nr u-padding-top-30" @click="showAddForm = false">
							暂不添加
						</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getUserProductList,
		addUserProduct,
		editUserProduct,
		setRecommendStatus,
		delUserProduct
	} from '@/yixu/api/user_product'

	export default {
		name: 'user-product-popup',
		props: {
			businessCardInformation: {
				type: Object,
				default: () => ({})
			},
			articleId: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				localShow: false,
				showAddForm: false,
				selectProduct: [],
				productList: [],
				formData: {
					name: '',
					limit: '',
					rate: '',
					advantage: ''
				},
				isEdit: false,
				rules: {
					name: [{
						required: true,
						message: '请输入产品名称',
						trigger: ['blur', 'change']
					}],
					limit: [{
						required: true,
						message: '请输入最高额度',
						trigger: ['blur', 'change']
					}],
					rate: [{
						required: true,
						message: '请输入年化利率',
						trigger: ['blur', 'change']
					}],
					advantage: [{
						required: true,
						message: '请输入产品优势',
						trigger: ['blur', 'change']
					}]
				}
			}
		},

		methods: {
			// 获取产品列表
			async getProductList() {
				try {
					const {
						code,
						data
					} = await getUserProductList({
						art_id: this.articleId
					})
					if (code === 1) {
						this.productList = data.map(item => ({
							...item,
							recommendations: item.recommendations === 1,
							checked: item.checked || false
						}))
					}
				} catch (e) {
					console.error(e)
				}
			},
			// 显示添加产品表单
			showAddProduct() {
				this.showAddForm = true
				this.isEdit = false
				this.formData = {
					name: '',
					limit: '',
					rate: '',
					advantage: ''
				}
			},
			// 提交表单
			async submitForm() {
				try {
					await this.$refs.uForm.validate()
					const submitData = {
						...this.formData
					}

					const {
						code
					} = this.isEdit ?
						await editUserProduct(submitData) :
						await addUserProduct(submitData)

					if (code === 1) {
						this.$u.toast(this.isEdit ? '编辑成功' : '添加成功')
						this.showAddForm = false
						this.getProductList()
					}
				} catch (e) {
					console.error(e)
				}
			},
			// 处理推荐状态变更
			async handleRecommendChange(item) {
				if (item.checked) {
					const checkedCount = this.productList.filter(item => item.checked).length;
					if (checkedCount > 5) {
						const firstCheckedIndex = this.productList.findIndex(p => p.checked);
						this.$set(this.productList[firstCheckedIndex], 'checked', false);
						this.$u.toast('最多只能选择5个产品展示');
					}
				}
				try {
					const { code } = await setRecommendStatus({
						id: item.id,
						art_id: this.articleId,
						is_show: item.checked ? 1 : 0
					});
					if (code !== 1) {
						item.checked = !item.checked;
						this.$u.toast('操作失败');
					}
				} catch (e) {
					console.error(e);
					item.checked = !item.checked;
					this.$u.toast('操作失败');
				}
			},
			// 编辑产品
			handleEdit(item) {
				this.showAddForm = true
				this.isEdit = true
				this.formData = {
					...item,
					recommendations: item.recommendations === 1
				}
			},
			// 删除产品
			async handleDelete(item) {
				try {
					const [err, res] = await uni.showModal({
						title: '提示',
						content: '确定要删除该产品吗？'
					})
					if (err) return
					if (res.confirm) {
						const {
							code
						} = await delUserProduct({
							id: item.id
						})
						if (code === 1) {
							this.$u.toast('删除成功')
							this.getProductList()
						}
					}
				} catch (e) {
					console.error(e)
				}
			},
			// 取消
			handleCancel() {
				this.$emit('cancel')
				this.localShow = false
			},
			// 确认
			handleConfirm() {
				const productIds = this.productList.filter(product => product.checked).map(item => item.id);
				this.$emit('confirm', productIds)
				this.localShow = false
			},
			showPopup() {
				this.getProductList()
				this.localShow = true
			}
		}
	}
</script>
<style lang="scss">
	.popup-bg {
		padding-top: 10vh;
		background: linear-gradient(180deg,
				rgba(255, 255, 255, 1) 0%,
				rgba(224, 242, 255, 1) 23.69%,
				rgba(110, 196, 255, 1) 72.53%,
				rgba(65, 178, 255, 1) 100%);
		background-image: url('https://resource.lanbaozixun.com/uploads/images/202407221641257d4b01953.png');
		background-repeat: no-repeat;
		background-size: 100% auto;
	}

	.form-area-bg {
		border-radius: 30rpx 30rpx 0 0;
		padding: 24rpx 24rpx 0;
		background: url('https://resource.lanbaozixun.com/uploads/images/20240722164943621888328.png');
		background-size: 100% 100%;
	}

	.form-area {
		background: white;
		padding: 12rpx 24rpx;
		border-radius: 30rpx 30rpx 0 0;
		padding-bottom: calc(60rpx + env(safe-area-inset-bottom));
	}

	.u-form-item {
		padding: 16rpx 0;
	}

	.uploader-container {
		width: 100%;

		.uplader-upload-slot {
			width: 100% !important;
			height: auto;
		}

		.column-center {
			width: 100%;

			.upload-area {
				width: 100%;
				height: 196rpx;
				border: 4rpx dashed #E5E5E5;
				border-radius: 10rpx;
				background-color: #FAFAFA;

				image {
					width: 74rpx;
					height: 64rpx;
				}
			}
		}
	}

	.product-operation-arar,
	.add-product-arar {
		height: 90vh;
		background: #F6F6F6;

		.hint-buy-vip-area {
			background: #E9F3FC;
			border-radius: 10rpx;
			border: 1px solid #A1D6FF;
		}
	}
</style>